package com.qire.manhua.model.viewModel.impl;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.view.View;
import android.widget.BaseAdapter;

import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.SmartRefreshViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.R;
import com.qire.manhua.controller.RecommendUpdateController;
import com.qire.manhua.dal.service.RecommendUpdateService;
import com.qire.manhua.databinding.LayoutHomeRecommendUpdateItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;

/**
 * 首页-推荐页-更新
 */
public class RecommendUpdateViewModel extends SmartRefreshViewModel<IViewModel> {

    private final RecommendUpdateService updateService = new RecommendUpdateService(this);

    private final ArrayList<UpdateComicItemViewModel> updateComicList = new ArrayList<>();

    private final SummerBindAdapter updateComicAdapter = new SummerBindAdapter(updateComicList);

    private int pageNo = 0;
    private long timeStamp = 0;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     */
    public void onAddition(RecommendUpdateController controller) {
        refreshUI();
        updateComicAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        updateComicAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #业务数据 begin

    /**
     * 重置加载数据
     */
    public void loadUpdateComicData() {
        resetPage();
        updateService.loadPageData();
    }

    /**
     * 加载更多数据
     */
    public void moreUpdateComicData() {
        updateService.loadPageData();
    }

    /**
     * 重置分页，重新开始刷新数据
     */
    private void resetPage() {
        timeStamp = System.currentTimeMillis() / 1000L;
        pageNo = 1;
    }

    /**
     * 翻页，下一页
     */
    public void nextPage() {
        pageNo++;
    }

    /**
     * @return 当前页号
     */
    public int pageNo() {
        return pageNo;
    }

    /**
     * @return 首次请求时间
     */
    public long timeStamp() {
        return timeStamp;
    }

    /**
     * @return true 则表示当前是第一页，否则 false
     */
    public boolean isFirstPage() {
        return pageNo == 1;
    }

    public void clearUpdateComicList() {
        updateComicList.clear();
    }

    public void addUpdateComicItem(int comicId, String comicName, String coverImg, int latestChapterId, String chapterTitle,
                                   String typeTag, String typeTagBgColor, String updateTime) {
        int serialNumber = updateComicList.size();
        updateComicList.add(new UpdateComicItemViewModel(comicId, comicName, coverImg, latestChapterId, chapterTitle,
                typeTag, typeTagBgColor, updateTime, serialNumber));
    }

    public void refreshUpdateComicAdapter() {
        updateComicAdapter.notifyDataSetChanged();
    }

    //endregion #业务数据 end

    // region #UI操作
    public void refreshUI() {
        refreshErrorDataUI();
    }
    public void refreshErrorDataUI() {
        set("errorLayoutVisible", ListUtil.isEmpty(updateComicList) ? View.VISIBLE : View.GONE);
    }
    // endregion

    // region #UI属性绑定
    public MutableLiveData<Integer> getErrorLayoutVisible() {
        return get("errorLayoutVisible");
    }

    public BaseAdapter getUpdateComicAdapter() {
        return updateComicAdapter;
    }
    // endregion

    @AdapterEntityBind(viewRid = R.layout.layout_home_recommend_update_item)
    public class UpdateComicItemViewModel extends BaseObservable implements AutoVariable<LayoutHomeRecommendUpdateItemBinding> {

        public final int    comicId;
        public final String comicName;
        public final String coverImg;
        public final int    latestChapterId;
        public final String chapterTitle;
        public final String typeTag;
        public final String typeTagBgColor;
        public final String updateTime;
        public final int    serialNumber;

        public UpdateComicItemViewModel(int comicId, String comicName, String coverImg, int latestChapterId, String chapterTitle,
                                        String typeTag, String typeTagBgColor, String updateTime, int serialNumber) {
            this.comicId = comicId;
            this.comicName = comicName;
            this.coverImg = coverImg;
            this.latestChapterId = latestChapterId;
            this.chapterTitle = chapterTitle;
            this.typeTag = typeTag;
            this.typeTagBgColor = typeTagBgColor;
            this.updateTime = updateTime;
            this.serialNumber = serialNumber;
        }

        @Override
        public void bindVariable(LayoutHomeRecommendUpdateItemBinding viewBind) {
            viewBind.setUpdateComicItemViewModel(this);
        }

        @Bindable
        public int getTypeTagVisible() {
            return StringUtil.isEmpty(typeTag) ? View.GONE : View.VISIBLE;
        }

        @Bindable
        public GradientDrawable getTypeTagBg() {
            // 创建渐变的shape drawable
//            int colors[] = { 0xff255779 , 0xff3e7492, 0xffa6c0cd };//分别为开始颜色，中间夜色，结束颜色
//            GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
            // 创建drawable
            GradientDrawable drawable = new GradientDrawable();

            int roundRadius = EquipmentInfoUtil.dip2px(2);  // 5dp 圆角半径
            int fillColor   = Color.parseColor(typeTagBgColor);     // 内部填充颜色    例：Color.parseColor("#FF00FF00");
            int strokeWidth = 1;                                    // 1dp 边框宽度
            int strokeColor = Color.parseColor(typeTagBgColor);     // 边框颜色       例：Color.parseColor("#FFFF0000");

            drawable.setColor(fillColor);
            drawable.setCornerRadius(roundRadius);
            drawable.setStroke(strokeWidth, strokeColor);
            drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);

            return drawable;
        }

        public ComicBookEntity toComicBookEntity(){
            // todo: 需要处理本地历史数据问题
//            DBBook dbBook = DBManager.getInstance().queryBook(bookId);
//            int lastReadChapterId = dbBook == null ? latestChapterId : dbBook.getChapter_id_recent();
            int lastReadChapterId = latestChapterId;
            return new ComicBookEntity(comicId, comicName, lastReadChapterId);
        }

    }

}
